package code.example.base.reflect.instrospector;

import code.example.tool.LogFactory;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class TestProperty {

    public void test() throws  Exception {
        BeanInfo beanInfo =  Introspector.getBeanInfo(SimpleBean.class);
        PropertyDescriptor pds [] =  beanInfo.getPropertyDescriptors();
        LogFactory.getLog().info(beanInfo.getBeanDescriptor().getName()+" properties:");
        PropertyDescriptor namePropertyDescriptor = null;
        for(int i=0;i<pds.length;i++){
            PropertyDescriptor pd = pds[i];
            String propertyName = pd.getName();
            Class propertyType = pd.getPropertyType();
            Method readMethod = pd.getReadMethod();
            Method writeMethod = pd.getWriteMethod();
            LogFactory.getLog().info("  property:"+propertyType.getName()+" "+propertyName+",readMethod:"+(readMethod != null)+", writeMethod:"+(writeMethod != null));
            if(pd.getName().equals("name")){
                namePropertyDescriptor = pd;
            }
        }
        LogFactory.getLog().info(beanInfo.getBeanDescriptor().getName()+" name property write and get :");
        String propertyValue = "Coke";
        Object simpleBeanInstance = SimpleBean.class.newInstance();
        Method readMethod = namePropertyDescriptor.getReadMethod();
        Method writeMethod = namePropertyDescriptor.getWriteMethod();
        LogFactory.getLog().info("  write property value:"+propertyValue);
        writeMethod.invoke(simpleBeanInstance,propertyValue);
        Object result = readMethod.invoke(simpleBeanInstance,null);
        LogFactory.getLog().info("  get property value:"+result);
    }
    public static void main(String []args ){
        try {
            new TestProperty().test();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
